package com.mesmileAI.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mesmileAI.entity.*;
import com.mesmileAI.service.ApiConfigService;
import com.mesmileAI.service.SmileTextService;
import com.mesmileAI.service.SmlieIndexService;
import com.theokanning.openai.client.OpenAiApi;
import com.theokanning.openai.completion.chat.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import com.theokanning.openai.service.OpenAiService;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import okhttp3.OkHttpClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import retrofit2.Retrofit;


import java.io.IOException;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;
import java.util.*;

import static com.theokanning.openai.service.OpenAiService.*;


/*
 *  chatGpt调用模块
 */
@RestController
@AllArgsConstructor
@Slf4j
@Tag(name = "chatGpt的api请求")
@RequestMapping("")
public class ChatController {


    @Resource
    SmileTextService smileTextService;

    @Resource
    SmlieIndexService smlieIndexService;

    @Resource
    ApiConfigService apiConfigService;

    @PostMapping ("/session")
    @Operation(summary = "验证机制")
//    @CrossOrigin(origins = "http://localhost:8080",methods = RequestMethod.POST)
    public Session presession(HttpServletResponse response){
        Session s= new Session();
        Mess mess = new Mess();
        mess.setAuth(false);
        mess.setModel("ChatGPTAPI");
        s.setData(mess);
        s.setStatus("Success");
        return s;
    }


    @PostMapping("/verify")
    @Operation(summary = "验证机制")
    public Session verify(){
        Session s= new Session();
        Mess mess = new Mess();
        mess.setAuth(false);
        mess.setModel("ChatGPTAPI");
        s.setData(mess);
        s.setStatus("Success");
        return s;
    }


    //api请求
    @PostMapping("/chat-process")
    @Operation(summary = "chat文本请求")
    @ResponseBody
    public StreamingResponseBody requestToChat(@RequestBody AcceptMessage acceptMassage, HttpServletResponse response) {
        return ConnectToChatGpt(acceptMassage,response);
    }


    //连接chatGpt
    private StreamingResponseBody ConnectToChatGpt(AcceptMessage acceptMassage,HttpServletResponse response){
        //使用当前config
        QueryWrapper<ApiConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApiConfig::getApiAddress,"openai.com");
        ApiConfig apiConfig = apiConfigService.getOne(queryWrapper);
        //开启代理
        ObjectMapper mapper = defaultObjectMapper();
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1",10809));
        OkHttpClient client = defaultClient(apiConfig.getApiKey(), Duration.ofSeconds(50))
                .newBuilder()
                .proxy(proxy)
                .build();
        Retrofit retrofit = defaultRetrofit(client, mapper);
        OpenAiApi api = retrofit.create(OpenAiApi.class);
        OpenAiService service = new OpenAiService(api);

        //直连，不开启代理
//        OpenAiService service = new OpenAiService(apiConfig.getApiKey(), Duration.ofSeconds(50));
        log.info("\nCreating completion...");
        System.out.println("传递的文本" + acceptMassage.getPrompt());
        if (!Objects.equals(acceptMassage.getOptions().toString(),null)){
            System.out.println("是否存储上下文 :是");
        }else {
            System.out.println("是否存储上下文 ：否");
        }
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(acceptMassage.getPrompt());
        String keywordId = acceptMassage.getKeywordId();
        //添加提示词
        if (!Objects.equals(keywordId,null)){
            SmlieIndex byId = smlieIndexService.getById(keywordId);
            stringBuffer.append(byId.getTextAll());
        }
        //添加携带的文本
        stringBuffer.append("///");
        acceptMassage.getIds().forEach(i->{
            stringBuffer.append(smileTextService.getById(i).getTextPice());
        });
        final List<ChatMessage> messages = new ArrayList<>();

        final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), acceptMassage.getSystemMessage());

        final ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), stringBuffer.toString());
        messages.add(systemMessage);
        messages.add(chatMessage);
        //添加上下文,清空buffer
//        if (!Objects.equals(acceptMassage.getOptions().getParentMessageId(),null)){
//            if (!Objects.equals(contentNext,null)){
//                stringBufferList.add(contentNext);
//                //刷新为空
//                contentNext= new StringBuffer();
//                //将内容添加进去
//                stringBufferList.forEach(i->{
//                    if (!Objects.equals(i.toString(),"")){
//                    ChatMessage nextMessage = new ChatMessage(ChatMessageRole.ASSISTANT.value(),i.toString());
//                    messages.add(nextMessage);
//                    }
//                });
//            }
//        }
//        else {
//            //清空
//            stringBufferList=new ArrayList<>();
//        }
        messages.forEach(i->log.info(i.toString()));
        //设置参数
        ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
                //chatGpt4Turbo
                .model("gpt-4")
//                .model("gpt-3.5-turbo")
//                .model("gpt-3.5-turbo-16k")
                .temperature(acceptMassage.getTemperature())
                .maxTokens(6000)
                .messages(messages)
                .stream(true)
                .presencePenalty(1.00)
                .user("meSmileChatBot")
                .topP(1.00)
                .build();
        //对话模型，传递出回复的答案，需要其他参数的时候说
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache");

        StringBuilder stringBuilder = new StringBuilder();
//       service.streamChatCompletion(completionRequest).doOnError(Throwable::printStackTrace).blockingForEach(System.out::println);
        return outputStream -> {
            outputStream.write("\n".getBytes());
            service.streamChatCompletion(completionRequest).doOnError(Throwable::printStackTrace).blockingForEach(i -> {
                String str = "";
                String uuid = UUID.randomUUID().toString();
                HashMap<String, String> stringStringHashMap = new HashMap<>();
                if (i.getChoices().get(0).getMessage().getContent()!=null){
                    stringBuilder.append(i.getChoices().get(0).getMessage().getContent());
                    //静态存储变量获得上下文
//                    contentNext.append(i.getChoices().get(0).getMessage().getContent());
                }
                //添加到上下文
                OpenApiResult openApiResult = new OpenApiResult();
                openApiResult.setId(i.getId());
                openApiResult.setRole(str);
                openApiResult.setParentMessageId(uuid);
                openApiResult.setText(stringBuilder.toString());
                openApiResult.setDelta(i.getChoices().get(0).getMessage().getContent());
                OpenApiDetail openApiDetail = new OpenApiDetail();
                openApiDetail.setId(i.getId());
                openApiDetail.setObject(i.getObject());
                openApiDetail.setCreated(i.getCreated());
                openApiDetail.setModel(i.getModel());
                ArrayList<Map<String, Object>> hashMaps = new ArrayList<>();
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("index", i.getChoices().get(0).getIndex());
                stringObjectHashMap.put("finish _reason", i.getChoices().get(0).getFinishReason());
                stringStringHashMap.put("content", i.getChoices().get(0).getMessage().getContent());
                stringObjectHashMap.put("delta", stringStringHashMap);
                hashMaps.add(stringObjectHashMap);
                openApiDetail.setChoices(hashMaps);
                openApiResult.setDetail(openApiDetail);
                outputStream.write(JSON.toJSONBytes(openApiResult));
                outputStream.write("\n".getBytes());
                outputStream.flush();
            });
        };
    }

    //连接千帆
    private void ConnectToQianFan(AcceptMessage acceptMessage,HttpServletResponse response){
        //先获取accesstoken
        RestTemplate template = new RestTemplate();
        //请求url
        String url ="https://aip.baidubce.com/oauth/2.0/token";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("grant_type","client_credentials");
        jsonObject.put("client_id","");
        jsonObject.put("client_secret","");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json"));

//        String token = template.postForObject(url,String.class,jsonObject)
        //传送的数据
        final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), acceptMessage.getSystemMessage());

    }
}
